package coder.nav.service;

import coder.nav.mapper.NavUserMapper;
import coder.nav.model.NavUser;
import coder.nav.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class NavUserService extends ServiceImpl<NavUserMapper, NavUser> {

    /**
     * 通过请求头token获取用户信息
     */
    public NavUser getByToken() {
        Long userId = JwtUtils.getUserId();
        if(Objects.isNull(userId)) {
            return null;
        }
        return this.getById(userId);
    }

    /**
     * 通过token获取用户信息
     */
    public NavUser getByToken(String token) {
        if(!JwtUtils.checkToken(token)) {
            return null;
        }
        Long userId = JwtUtils.getUserIdByToken(token);
        if(Objects.isNull(userId)) {
            return null;
        }
        return this.getById(userId);
    }

    /**
     * 通过账号密码获取用户信息
     * @param username 账号
     * @param password 密码
     */
    public NavUser getByUsernameAndPassword(String username, String password) {
        LambdaQueryWrapper<NavUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NavUser::getUsername, username);
        queryWrapper.eq(NavUser::getPassword, DigestUtils.md5Hex(password));
        return this.getOne(queryWrapper);
    }

    /**
     * 通过账号密码获取用户信息（经过加密的）
     * @param username 账号
     * @param md5pwd 密码（经过加密的）
     */
    public NavUser getByUsernameAndMd5pwd(String username, String md5pwd) {
        LambdaQueryWrapper<NavUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NavUser::getUsername, username);
        queryWrapper.eq(NavUser::getPassword, md5pwd);
        return this.getOne(queryWrapper);
    }

    /**
     * 修改账号昵称
     * @param username 修改后的账号昵称
     */
    public void setUsernameByToken(String username) {
        LambdaUpdateWrapper<NavUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(NavUser::getId, JwtUtils.getUserId())
                .set(NavUser::getUsername, username);
        this.update(updateWrapper);
    }

    /**
     * 修改账号密码
     * @param password 修改后的账号密码
     */
    public void setPasswordByToken(String password) {
        if(StringUtils.isBlank(password)) {
            throw new RuntimeException("请输入新密码");
        }
        LambdaUpdateWrapper<NavUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(NavUser::getId, JwtUtils.getUserId())
                .set(NavUser::getPassword, DigestUtils.md5Hex(password));
        this.update(updateWrapper);
        // JwtUtils.cleanToken();
    }

}
